﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Evpo.ContactData.ViewModel;
using Evpo.ContactData.Common;

namespace Evpo.ContactData.UI
{
    public partial class LinkedGroupEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ViewModel = new LinkedGroupEditViewModel(
                new ModelFactory(),
                (IConnection)Session[SessionStateKeys.Connection],
                Int32.Parse(Request["ID"]));

            uiRelationshipTypes.DataSource = ViewModel.RelationshipTypes();
            
            if (!IsPostBack)
            {
                uiLinkedGroup.DataSource = ViewModel.ContactLinks(ViewModel.ContactID);
                uiLinkedGroup.DataBind();
                uiRemove.DataBind();
                uiRelationshipTypes.DataBind();
                uiContactInList.DataBind();
            }
        }

        #region Handlers
        protected void uiAddRelationship_Click(object sender, EventArgs e)
        {
            foreach (int contactID in uiContactList.SelectedItems())
            {
                IRelationship relationship = ViewModel.CreateRelationship();
                relationship.RelatedContactID = contactID;
                relationship.RelationshipType = Int32.Parse(uiRelationshipTypes.SelectedValue);
                ViewModel.SaveRelationship(relationship);
            }

            RefreshData();
        }

        protected void uiRemove_Click(object sender, EventArgs e)
        {
            foreach (int relatedContactID in uiLinkedGroup.SeletedContacts())
            {
                ViewModel.DeleteRelationship(ViewModel.ContactID, relatedContactID);
            }

            RefreshData();
        }

        #endregion Handlers

        #region Fields
        #endregion

        #region Properties
        public LinkedGroupEditViewModel ViewModel;
        #endregion



        #region Methods

        private void RefreshData()
        {
            uiContactList.RefreshList();
            uiLinkedGroup.DataSource = ViewModel.ContactLinks(ViewModel.ContactID);
            uiLinkedGroup.DataBind();
            uiRemove.DataBind();
            uiContactInList.DataBind();
        }

        #endregion


    }
}